package com.quanyan.place.web;

import com.alibaba.fastjson.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.enums.SysParameterConfigEnum;
import com.quanyan.common.user.AppUserCacheInfo;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.common.utils.UUIDUtils;
import com.quanyan.place.cache.PlaceRedisTemplate;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.*;
import com.quanyan.place.entity.apireq.ReqPlaceInfo;
import com.quanyan.place.entity.vo.*;
import com.quanyan.place.service.*;
import com.quanyan.place.wrapper.PlaceUnitSalePlanWrapper;
import com.quanyan.place.wrapper.PlaceWrapper;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.redisCluster.utils.RedisKey;
import com.quanyan.sms.service.SmsService;
import com.quanyan.user.request.ReqAppUserLogin;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import sms.SmsApi;
import sms.model.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.util.*;

import static com.quanyan.place.constants.PlaceConstants.UNIT_TYPE_BASE;

/**
 * Created by yangyun on 2016/4/14.
 */

@RestController
@RequestMapping("/admin/api/place")
public class PlaceController {

    @Autowired
    PlaceInnerService placeService;

    @Autowired
    PlaceBaseService placeBaseService;

    @Autowired
    PlaceSaleService placeSaleService;

    @Autowired
    SmsService smsService;

    @Autowired
    AdminUserService adminUserService;

    @Autowired
    PlaceWrapper placeWrapper;

    @Autowired
    PlaceUnitSalePlanWrapper placeUnitSalePlanWrapper;

    @Autowired
    BaseService baseService;

    @Value("${SOLRCLOUD.SERVER.URL}")
    String solrUrl;

    @Autowired
    UserServiceFacade userServiceFacade;

    @Autowired
    UserService userService;

    @Autowired
    PlaceRedisTemplate placeRedisTemplate;

    @Autowired
    PlaceInnerService placeInnerService;

    @Autowired
    com.quanyan.place.biz.SmsService  placeSmsService;

    private Logger logger = LoggerFactory.getLogger(PlaceController.class);


    /**
     * 导入场馆索引
     * @return
     */
    @RequestMapping("/importIndex")
    public String importIndex(@RequestBody Map map){
        return placeWrapper.importIndex(map, solrUrl);
    }


    /**
     * 导入场馆索引
     * @return
     */
    @RequestMapping("/importIndexByTerm")
    public String importIndexByTerm(@RequestBody Map map){
        return placeWrapper.importIndexByTerm(map, solrUrl);
    }

    /**
     * 导入指定的场馆索引
     * @return
     */
    @RequestMapping("/importPlacesIndex")
    public String importPlacesIndex(@RequestBody Map map){
        String placeids = MapUtils.getString(map, "placeids");
        return placeWrapper.importPlacesIndex(placeids);
    }

    @RequestMapping("/importSignIndex")
    public APIResponse<?> importSignIndex(@RequestBody Map map){
        return placeWrapper.importIndex(map);
    }

    /**
     * 获取场馆基本信息接口
     * @return
     */
    @RequestMapping("/placeCommonData")
    public @ResponseBody String placeCommonData() {
        String result = JSON.toJSONString(this.placeService.getPlaceCommonData());
        return result;
    }


    /**
     * 场馆录入接口
     * @param placeFromDataVo
     * @return
     */
    @RequestMapping(value = "/importPlaceData", method = RequestMethod.POST)
    public APIResponse<?> importPlaceData(@RequestBody PlaceFromDataVo placeFromDataVo)  {
        APIResponse apiResponse = placeWrapper.saveOrUpdatePlace(placeFromDataVo);
        return apiResponse;
    }

    /**
     * 片场录入接口
     * @param placeFromDataVo
     * @return
     */
    @RequestMapping(value = "/importPlaceUnitData", method = RequestMethod.POST)
    public APIResponse<?> importPlaceUnitData(@RequestBody PlaceFromDataVo placeFromDataVo)  {
        APIResponse apiResponse = placeWrapper.savePlaceUnitData(placeFromDataVo);
        return apiResponse;
    }

    /**
     * 获取提供商信息接口
     * @param reqSupplierSearchVo
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/supplierData")
    public APIResponse<?> supplierData(@RequestBody @Valid ReqSupplierSearchVo reqSupplierSearchVo,BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        return APIResponse.returnSuccess(this.placeService.getSupplierData(reqSupplierSearchVo));
    }

    /**
     * 获取省信息接口
     * @return
     */
    @RequestMapping("/provinceData")
    public @ResponseBody String provinceData() {
        String result = JSON.toJSONString(this.placeService.getProvinceData());
        return result;
    }

    /**
     * 获取城市信息接口
     * @param provinceId  省id
     * @return
     */
    @RequestMapping("/cityData")
    public @ResponseBody String cityData(@RequestParam(value = "provinceId", required = false) Integer provinceId) {
        String result = JSON.toJSONString(this.placeService.getCityData(provinceId, true));
        return result;
    }


    /**
     * 获取区域信息接口
     * @param cityId   城市id
     * @return
     */
    @RequestMapping("/districtData")
    public @ResponseBody String districtData(@RequestParam("cityId") int cityId) {
        String result = JSON.toJSONString(this.placeService.getDistrictData(cityId));
        return result;
    }

    /**
     * 获取片场信息接口
     * @param placeId       获取场馆id为placeId的所有片场信息
     * @param placeUnitId   获取片场id为placeUnitId的片场信息
     * @return
     */
    @RequestMapping("/placeUnitData")
    public @ResponseBody String getPlaceUnitData(@RequestParam("placeId") int placeId,
                                                 @RequestParam("placeUnitId") int placeUnitId) {
        String result = JSON.toJSONString(this.placeService.getPlaceUnitData(placeId, placeUnitId));
        return result;
    }

    /**
     * 获取场地详情接口
     * @param placeUnitId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getPlaceUnitDetailData")
    public @ResponseBody String getPlaceUnitDetailData(@RequestParam("placeUnitId") int placeUnitId) throws Exception{
        String result = JSON.toJSONString(this.placeService.getPlaceUnitDetailData(placeUnitId));
        return result;
    }

    /**
     * 获取场馆详情接口
     * @param placeId
     * @return
     */
    @RequestMapping("/placeDetailData")
    public @ResponseBody String getPlaceDetailData(@RequestParam(value = "placeId",required = true) int placeId) {

        String result = JSON.toJSONString(this.placeService.getPlaceDetailData(placeId));

        return result;
    }

    /**
     * 获取场馆经营运动类型
     * @param placeId
     * @return
     */
    @RequestMapping("/getPlaceCategory")
    public APIResponse<?> getPlaceCategory(@RequestParam(value = "placeId",required = true) Integer placeId) {

        PlaceCategoryVo placeCategoryVo = placeService.getPlaceCategory(placeId);

        return APIResponse.returnSuccess(placeCategoryVo);
    }


    /**
     * 获取场馆销售计划
     * @param placeId
     * @param categoryId
     * @return
     */
    @RequestMapping(value = "/getPlaceInfoForPricing")
    public APIResponse<?> getPlaceInfoForPricing(@RequestParam(value = "placeId",required = true) Integer placeId,
                                                 @RequestParam(value = "categoryId",required = false) Byte categoryId) {

        List<PlaceUnitSalePlan> result = placeUnitSalePlanWrapper.getPlaceUnitSalePlan(placeId, categoryId);
        return APIResponse.returnSuccess(result);
    }

    /**
     * 获取场地列表
     * @param reqPlaceSearch
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/getPlaceList", method = RequestMethod.POST)
    public APIResponse<?> getPlaceList(@RequestBody @Valid ReqPlaceSearch reqPlaceSearch, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }

        return APIResponse.returnSuccess(placeWrapper.getPlaceList(reqPlaceSearch));
    }

    /*
    新增拜访记录模块获取场地列表(分页)
     */
    @RequestMapping(value = "/getPlacesRistorRecord", method = RequestMethod.POST)
    public APIResponse<?> getPlacesRistorRecord(@RequestBody ReqPlaceSearch reqPlaceSearch) {
        return APIResponse.returnSuccess(placeService.getPlacesRistorRecord(reqPlaceSearch));
    }

    /**
     * 保存场地销售计划(单个)
     * @param placeUnitSalePlan
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/savePlaceSalePlanSingle", method = RequestMethod.POST)
    public APIResponse<PlaceUnitSalePlan> savePlaceSalePlanSingle(@RequestBody @Valid PlaceUnitSalePlan placeUnitSalePlan, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        //判断是否存在该场馆的销售计划，不存在删场馆索引
        placeService.isExsit(placeUnitSalePlan.getPlaceId());
        TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_PLACE_SALEPLAN_SYNC_PERIOD.getCode());
        int period = PlaceConstants.DEFAULT_PRICE_WEEK_PERIOD;  // 需要同步的周期
        if (parameter != null && parameter.getParameterValue() != null){
            period = Integer.valueOf(parameter.getParameterValue());
        }
        List<String> errorMessage = placeService.saveSinglePlaceSalePlan(placeUnitSalePlan,period, UNIT_TYPE_BASE);
        if (null != placeUnitSalePlan && null != placeUnitSalePlan.getPlaceId()){
            // 更新最低价
            placeInnerService.getMinPrice(placeUnitSalePlan);
            // 将placeId放入缓存，用于批量更新到solr服务器
            placeWrapper.setPlaceIdToCache(placeUnitSalePlan.getPlaceId(), placeRedisTemplate);
        }
        if (errorMessage.size() > 0){
            return APIResponse.returnFail(errorMessage.toString());
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 保存场地销售计划(批量)
     * @param placeUnitSalePlanVo
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/savePlaceSalePlanBatch", method = RequestMethod.POST)
    public APIResponse<?> savePlaceSalePlanBatch(@RequestBody @Valid PlaceUnitSalePlanVo placeUnitSalePlanVo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }

        TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_PLACE_SALEPLAN_SYNC_PERIOD.getCode());
        int period = PlaceConstants.DEFAULT_PRICE_WEEK_PERIOD;  // 需要同步的周期
        if (parameter != null && parameter.getParameterValue() != null){
            period = Integer.valueOf(parameter.getParameterValue());
        }
        List<String> errorMessage = placeService.savePlaceSalePlanBatch(placeUnitSalePlanVo.getSalePlanList(), period, UNIT_TYPE_BASE);

        if (null != placeUnitSalePlanVo && null != placeUnitSalePlanVo.getPlaceId()){
            // 更新最低价
            PlaceUnitSalePlan placeUnitSalePlan = new PlaceUnitSalePlan();
            placeUnitSalePlan.setPlaceId(placeUnitSalePlanVo.getPlaceId());
            placeUnitSalePlan.setCategoryId(placeUnitSalePlanVo.getCategoryId().intValue());
            placeInnerService.getMinPrice(placeUnitSalePlan);
            // 将placeId放入缓存，用于批量更新到solr服务器
            placeWrapper.setPlaceIdToCache(placeUnitSalePlanVo.getPlaceId(), placeRedisTemplate);
        }
        if (errorMessage.size() > 0){
            return APIResponse.returnFail(errorMessage.toString());
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 同步最新价格及销售计划到搜索引擎
     * @return
     */
    @RequestMapping(value = "/syncPlaceSalePlanToSearchEngine")
    public APIResponse<?> syncPlaceSalePlanToSearchEngine(@RequestParam(value = "placeId",required = true) Integer placeId){
        return placeWrapper.syncPlaceSalePlanToSearchEngine(placeId);
    }


    /**
     * 获取运动种类信息接口
     * @return
     */
    @RequestMapping(value = "/getCagetoryList")
    public String cagetoryList() {
        String result = JSON.toJSONString(this.placeBaseService.getCategory());
        return result;
    }


    @RequestMapping(value = "/getPlaceListByName", method = RequestMethod.POST)
    public APIResponse<?> getPlaceListByName(HttpServletRequest request) {
        String placeName = request.getParameter("placeName");
        if(StringUtil.isBlankOrNull(placeName)){
            return  APIResponse.returnFail("场馆名称为空！");
        }
        return placeBaseService.selectPlaceByName(placeName);
    }

    /**
     * 场馆锁定
     * @param placeId
     * @return
     */
    @RequestMapping(value = "/lockPlace", method = RequestMethod.POST)
    public APIResponse<?> lockPlace(@RequestParam("placeId") Integer placeId,
                                    @RequestParam("uid") Integer uid){
        List<String> errMessage = new ArrayList<String>();
        TbBizPlace bizPlace = placeBaseService.getPlaceById(placeId);
        if (null != bizPlace){
            if (Constants.BYTE_ONE == bizPlace.getIsSign()){
                errMessage.add("已签约场馆不能锁定");
            }
        }
        if (null != uid){
            TbAdminUser user = adminUserService.getAdminUser(uid);
            if (null == user){
                errMessage.add("对不起,你无权操作");
            } else {
                placeService.lockPlace(bizPlace,user);
            }
        } else {
            errMessage.add("用户不能为空");
        }
        if (errMessage.size() > 0){
            return APIResponse.returnFail(errMessage.toString());
        } else {
            return APIResponse.returnSuccess();
        }
    }

    /**
     * 场馆解除锁定
     * @param placeId
     * @return
     */
    @RequestMapping(value = "/unlockPlace", method = RequestMethod.POST)
    public APIResponse<?> unlockPlace(@RequestParam("placeId") Integer placeId,
                                    @RequestParam("uid") Integer uid){
        List<String> errMessage = new ArrayList<String>();
        TbBizPlace bizPlace = placeBaseService.getPlaceById(placeId);
        if (null != bizPlace){
            if (Constants.BYTE_ONE == bizPlace.getIsSign()){
                errMessage.add("已签约场馆不能解除锁定");
            }
        }
        if (null != uid){
            TbAdminUser user = adminUserService.getAdminUser(uid);
            if (null == user){
                errMessage.add("对不起,你无权操作");
            } else {
                placeService.unlockPlace(bizPlace, user);
            }
        } else {
            errMessage.add("用户不能为空");
        }
        if (errMessage.size() > 0){
            return APIResponse.returnFail(errMessage.toString());
        } else {
            return APIResponse.returnSuccess();
        }
    }


    /*
   更改所属海域
    */
    @RequestMapping(value = "/updateStatus",method = RequestMethod.POST)
    public APIResponse<?> updateStatus(){
        placeService.updateStatus();
        return null;
    }


    @RequestMapping(value = "/getPlaceUnitListById", method = RequestMethod.POST)
    public APIResponse<?> getPlaceUnitList(HttpServletRequest request) {
        String placeId = request.getParameter("placeId");
        if(StringUtil.isBlankOrNull(placeId)){
            APIResponse.returnFail("场馆id为空！");
        }
        return APIResponse.returnSuccess(placeBaseService.getPlaceUnitByPlaceId(Integer.parseInt(placeId),null, false));
    }

    /**
     * 更新片场信息接口
     * @param tbBizPlaceUnitVo
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/updatePlaceUnitData")
    public APIResponse<?> updatePlaceUnitData(@RequestBody @Valid TbBizPlaceUnitVo tbBizPlaceUnitVo,BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        return placeService.updatePlaceUnitData(tbBizPlaceUnitVo);
    }


    /**
     * 更新场馆信息接口
     * @param placeFromDataVo
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/updatePlaceData" , method = RequestMethod.POST)
     public APIResponse<?> updatePlaceData(@RequestBody @Valid PlaceFromDataVo placeFromDataVo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        return this.placeWrapper.updatePlaceData(placeFromDataVo);
    }


    /**
     * 取得商务场馆分布数据
     * @param cityId
     * @param districtId
     * @param category
     * @param request
     * @return
     */
    @RequestMapping(value = "getPlaceDistribution")
    @ResponseBody
    public APIResponse<?> getPlaceDistribution(@RequestParam(value = "cityId", required = false) Integer cityId,
                                               @RequestParam(value = "districtId", required = false) Integer districtId,
                                               @RequestParam(value = "category", required = false) Integer category,
                                               @RequestParam(value = "primeType", required = false) Integer primeType,
                                               @RequestParam(value = "isSign", required = false) Integer isSign,
                                               HttpServletRequest request) {
       PlaceDistribution result = null;
        try {
            result =  placeService.getPlaceDistribuctionGroup(cityId, category, districtId, primeType, isSign);
            return APIResponse.returnSuccess(result);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return APIResponse.returnFail(e.getMessage());
        }
    }

    /**
     * 取得商务场馆地图详细
     * @param placeId
     * @param unitId
     * @param request
     * @return
     */
    @RequestMapping(value = "getPlaceSignDetailGroup")
    @ResponseBody
    public APIResponse<?> getPlaceSignDetailGroup(@RequestParam(value = "placeId", required = false) Integer placeId,
                                                  @RequestParam(value = "unitId", required = false) Integer unitId,
                                                  HttpServletRequest request) {
        PlaceKpiInfo result = null;
        try {
            result =  placeService.getPlaceSignDetailData(placeId);
            return APIResponse.returnSuccess(result);
        } catch (Exception e) {
            return APIResponse.returnFail(e.getMessage());
        }
    }

    /**
     * 取得商务场馆销售情况
     * @param cityId
     * @param districtId
     * @param category
     * @param request
     * @return
     */
    @RequestMapping(value = "getPlaceSaleDistribution")
    @ResponseBody
    public APIResponse<?> getPlaceSaleDistribution(@RequestParam(value = "cityId", required = false) Integer cityId,
                                               @RequestParam(value = "districtId", required = false) Integer districtId,
                                               @RequestParam(value = "category", required = false) Integer category,
                                               HttpServletRequest request) {
        PlaceSaleDistribution result = null;
        try {
            result =  placeService.getPlaceSaleDistribuctionGroup(cityId, category, districtId);
            return APIResponse.returnSuccess(result);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return APIResponse.returnFail(e.getMessage());
        }
    }


    /**
     * 取得商务场馆签约和销售比例
     * @param placeId
     * @param unitId
     * @param request
     * @return
     */
    @RequestMapping(value = "getPlaceSignAndSaleRate")
    @ResponseBody
    public APIResponse<?> getPlaceSignAndSaleRate(@RequestParam(value = "placeId", required = false) Integer placeId,
                                               @RequestParam(value = "unitId", required = false) Integer unitId,
                                               @RequestParam(value = "startTime", required = false) String startTime,
                                               @RequestParam(value = "endTime", required = false) String endTime,
                                               HttpServletRequest request) {
        PlaceKpiInfo result = null;
        try {
            Date startDate = null;
            Date endDate = null;
            Calendar calEndDate = Calendar.getInstance();
            if (!StringUtil.isBlankOrNull(startTime)){
                startDate = DateUtils.strToDate(startTime, DateUtils.DATE_FORMAT_yyyy_MM_dd);
            }
            if (!StringUtil.isBlankOrNull(endTime)){
                endDate = DateUtils.strToDate(endTime, DateUtils.DATE_FORMAT_yyyy_MM_dd);
                calEndDate.setTime(endDate);
                calEndDate.set(Calendar.HOUR_OF_DAY, 23);
                calEndDate.set(Calendar.MINUTE, 59);
                calEndDate.set(Calendar.SECOND, 59);
                endDate = calEndDate.getTime();
            }
            //result =  placeSaleService.getPlaceSignAndSaleRate(placeId, unitId, startDate, endDate);
            return APIResponse.returnSuccess(result);
        } catch (Exception e) {
            return APIResponse.returnFail(e.getMessage());
        }
    }

    /**
     * 删除场馆以及场馆下所有的片场信息
     * @param placeId
     * @return
     */
    @RequestMapping(value = "/delPlaceAndPlaceUnit")
    public APIResponse<?> delPlaceAndPlaceUnit(@RequestParam("placeId") Integer placeId){
        APIResponse result = placeWrapper.deletePlace(placeId);
        return result;
    }

    /**
     * 删除片场信息
     * @param placeUnitId
     * @return
     */
    @RequestMapping(value = "/delPlaceUnit")
    public APIResponse<?> delPlaceUnit(@RequestParam("placeUnitId") Integer placeUnitId){
        return placeWrapper.deletePlaceUnit(placeUnitId);
    }

    /**
     * 根据查询条件获取片场列表信息
     * @param reqPlaceUnitSearch
     * @return
     */
    @RequestMapping(value = "/getAllPlaceUnitList")
    public APIResponse<?> getAllPlaceUnitList(@RequestBody ReqPlaceUnitSearch reqPlaceUnitSearch) {
        return APIResponse.returnSuccess(placeService.getAllPlaceUnitList(reqPlaceUnitSearch));
    }

    /**
     * 场馆销售计划同步
     * @param
     * @return
     */
    @RequestMapping(value = "/syncPlaceSalePlan")
    public APIResponse<?> syncPlaceSalePlan(@RequestParam("placeId") Integer placeId) {
        placeService.copySalePlanFromModel(placeId, PlaceConstants.DEFAULT_PRICE_WEEK_PERIOD);
        return APIResponse.returnSuccess();
    }

    /**
     * 查询场馆运营规则设置
     * @param
     * @return
     */
    @RequestMapping(value = "/getPlaceOperationRule")
    public APIResponse<?> getPlaceOperationRule(@RequestParam("placeId") Integer placeId) {
        PlaceOperationRuleVo result = placeService.getPlaceOperationRule(placeId);
        return APIResponse.returnSuccess(result);
    }


    /**
     * 场馆运营规则设置
     * @param placeOperationRuleVo
     * @return
     */
    @RequestMapping(value = "/savePlaceOperationRule")
    public APIResponse<?> savePlaceOperationRule(@RequestBody PlaceOperationRuleVo placeOperationRuleVo) {
        boolean result = placeService.savePlaceOperationRule(placeOperationRuleVo);
        if (result){
            return APIResponse.returnSuccess();
        } else {
            return  APIResponse.returnFail("更新场馆运营规则失败");
        }

    }


    /**
     * 场馆推送短信
     * @param
     * @return
     */
    @RequestMapping(value = "/sendMessage")
    public APIResponse<?> sendMessage(@RequestBody ReqSendMessageBatch reqMessage) {
        if (reqMessage != null && reqMessage.getPhones() != null){
            if (reqMessage.getPhones().size() >= 50){
                return APIResponse.returnFail("一次发送的手机号码不能超过50个"); // TODO
            }
            for (String phone : reqMessage.getPhones()){
                smsService.sendMessageToPhone(phone, SmsApi.MESSAGE_TEMPLATE_USER_EXAMINE_YES, new String[]{reqMessage.getContent()},false);
            }
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 发送验证码
     * @param
     * @return
     */
    @RequestMapping(value = "/sendValidCodetToPhone")
    public APIResponse<?> sendValidCodetToPhone(@RequestParam("phone") String phone) {

        //Result result = smsService.sendValidCodetToPhone(phone, SmsApi.MESSAGE_TEMPLATE_USER_REFUND, 60, 120); // TODO
        //Result result = smsService.sendValidCodetToPhone(phone, SmsApi.MESSAGE_TEMPLATE_USER_REGISTER, 60, 120); // TODO
        List<String> mobileList=new ArrayList<>();
        List<String> paramList=new ArrayList<>();
        mobileList.add(phone);
        placeSmsService.sendSms(mobileList,1, PlaceConstants.PLACE_SMS_TYPE_VALIDCODE,paramList);
        /*if (result.isStatus()){
            return APIResponse.returnSuccess();
        } else {
            return APIResponse.returnFail(result.getMsg());
        }*/
        return APIResponse.returnSuccess();

    }

    /**
     * 校验验证码
     * @param
     * @return
     */
    @RequestMapping(value = "/verifyValidCode")
    public APIResponse<?> verifyValidCode(@RequestParam("phone") String phone,@RequestParam("code") String code,@RequestParam(value = "isLogin" ,required = false) Integer isLogin,HttpServletResponse httpServletResponse) {
        if(isLogin != null && Constants.IS_YES == isLogin){ //判断是否是登录注册验证功能

            /*//判断手机号是否存在，存在的话，进行登录
            User user = userService.getUserByMobile(phone);
            if(user == null){//用户不存在需要进行注册用户，再登录
                APIResponse apiResponse  = userService.userRegisterByMobile(phone);//TODO 以后会调用新的用户系统注册
                user = (User) apiResponse.getData();
            }
            String uuid = UUIDUtils.getUUID();
            AppUserCacheInfo appUserCacheInfo = new AppUserCacheInfo();
            appUserCacheInfo.setUser_id(user.getId());
            appUserCacheInfo.setCreate_time(new Date());
            appUserCacheInfo.setDev(3);
            String userInfo = JSON.toJSONString(appUserCacheInfo);
            placeRedisTemplate.set(uuid, userInfo, Constants.TOKEN_EXPIRED_TIME);//设置过期时间
            RedisKey redisKey = new RedisKey(RedisConstants.C_FAMILY_KEY, uuid);
            try {
                if (null != redisKey.getRedisKey() && redisKey.getRedisKey().length() > 0) {
                    AppUserCacheInfo appUserCacheInfo1 = (AppUserCacheInfo) placeRedisTemplate.getObjectFromC(redisKey, AppUserCacheInfo.class);
                    if (null != appUserCacheInfo1 && null != appUserCacheInfo1.getUser_id())
                    System.out.println("========" + appUserCacheInfo1.getUser_id());
                }
            } catch (UnsupportedEncodingException e) {
                logger.info("{}",e);
            }

            httpServletResponse.setHeader(Constants.USER_INFORMATION_MARK, uuid);
            return APIResponse.returnSuccess(uuid);*/

            ReqAppUserLogin reqAppUserLogin = new ReqAppUserLogin();
            reqAppUserLogin.setMobile(phone);
            reqAppUserLogin.setType(Constants.LoginType.VALID_CODE.byteValue());
            reqAppUserLogin.setValidCode(code);
            APIResponse<RespUserInfoBase> respUserInfoBaseAPIResponse = null;
            try {
                respUserInfoBaseAPIResponse = userServiceFacade.appLogin(reqAppUserLogin);
                if(respUserInfoBaseAPIResponse.isRet() && respUserInfoBaseAPIResponse.getData() != null){
                    RespUserInfoBase respUserInfoBase = respUserInfoBaseAPIResponse.getData();
                    logger.info("======登录注册验证成功 userCookiesName:{} ==> uid:{} =================", respUserInfoBase.getToken(),respUserInfoBase.getUid());
                    httpServletResponse.setHeader(Constants.USER_INFORMATION_MARK, respUserInfoBase.getToken());
                    return APIResponse.returnSuccess(respUserInfoBase.getToken());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return APIResponse.returnFail("");
        }
        //boolean result = smsService.verifyValidCode(phone, SmsApi.MESSAGE_TEMPLATE_USER_REFUND, code);
        // boolean result = smsService.verifyValidCode(phone, SmsApi.MESSAGE_TEMPLATE_USER_REGISTER, code);
        APIResponse response=placeSmsService.checkCode(code,phone);
        if (response.isRet()&&response.getErrcode()==200){
            return APIResponse.returnSuccess();
        } else {
            return APIResponse.returnFail("验证码错误");
        }

    }

    /**
     * 获得场馆信息
     * @param
     * @return
     */
    @RequestMapping(value = "/getPlaceByLikeName",method = RequestMethod.POST)
    public APIResponse<?> getPlaceByLikeName(@RequestBody ReqPlaceSearch reqPlaceSearch) {
      return  APIResponse.returnSuccess(placeBaseService.getPlaceByLikeName(reqPlaceSearch.getName(),0));
    }

    @RequestMapping(value = "/updatePlaceGroupId",method = RequestMethod.POST)
    public APIResponse<?> updatePlaceGroupId(@RequestBody ReqPlaceInfo reqPlaceInfo) {
        return  placeWrapper.updatePlaceGroupId(reqPlaceInfo);
    }

    @RequestMapping(value = "/getPlaceListByCategoryId",method = RequestMethod.POST)
    public APIResponse<?> getPlaceListByCategoryId(@RequestBody ReqPlaceSearch reqvo) {
        return  APIResponse.returnSuccess(placeWrapper.getPlaceListByCategoryId(reqvo));
    }

    /**
     * 操作场馆上下架
     * @param map
     * @return
     */
    @RequestMapping(value = "/changeShelveStatus")
    public APIResponse<?> changeShelveStatus(@RequestBody Map<String, Object> map){
        Integer placeId = MapUtils.getInteger(map, "placeId");
        Integer status = MapUtils.getInteger(map, "status");
        Integer uid = MapUtils.getInteger(map, "uid");
        if (StringUtils.isEmpty(placeId)){
            return APIResponse.returnFail("场馆Id不能为空");
        }
        if (StringUtils.isEmpty(status)){
            return APIResponse.returnFail("上下架状态不能为空");
        }
        if (status > 1){
            return APIResponse.returnFail("上下架状态错误");
        }
        APIResponse result = placeWrapper.isShelves(placeId, status);
        if (null != result && result.isRet()){
            placeWrapper.updateSolrIndex(placeId);
        }
        return result;
    }

    /**
     *  获取场馆项目及规模
     * @param
     * @return
     */
    @RequestMapping(value = "/getPlaceCategoryAndScale",method = RequestMethod.POST)
    public APIResponse<?> getPlaceCategoryAndScale(@RequestBody Map<String, Object> map) {
        Integer placeId = MapUtils.getInteger(map, "placeId");
        return  APIResponse.returnSuccess(placeBaseService.getCategoryAndScale(placeId, true));
    }

    /**
     * 删除指定场馆无效销售计划
     * @param
     * @return
     */
    @RequestMapping(value = "/delInvalidSalePlan")
    public APIResponse<?> delInvalidSalePlan(@RequestParam(value = "placeId", required = false) Integer placeId) {
        placeUnitSalePlanWrapper.delInvalidSalePlan(placeId);
        return  APIResponse.returnSuccess();
    }

    @RequestMapping(value = "/settingPrint",method = RequestMethod.POST)
    public APIResponse<?> settingPrint(@RequestBody Map<String, Object> map) {
        Integer placeId = MapUtils.getInteger(map, "placeId");
        Integer printNum = MapUtils.getInteger(map, "printNum");
        String printMemo = MapUtils.getString(map, "printMemo");
        return  placeBaseService.saveOrUpdatePrintSetting(placeId,printNum,printMemo);
    }

    @RequestMapping(value = "/getPrint",method = RequestMethod.POST)
    public APIResponse<?> getPrint(@RequestBody Map<String, Object> map) {
        Integer placeId = MapUtils.getInteger(map, "placeId");
        return  placeBaseService.getPrintSettingByPlaceId(placeId);
    }

    /**
     * 设置场地时段销售单元(0:半小时；1：1小时；2:2小时）
     * @param map
     * @return
     */
    @RequestMapping(value = "/setPlaceCategorySaleTimeUnit")
    public APIResponse<?> setPlaceCategorySaleTimeUnit(@RequestBody Map<String, Object> map){
        Integer placeId = MapUtils.getInteger(map, "placeId");
        Integer categoryId = MapUtils.getInteger(map, "categoryId");
        Byte timeUnit = MapUtils.getByte(map, "timeUnit",Constants.BYTE_ONE);
        Byte startSaleTimeType = MapUtils.getByte(map, "startSaleTimeType",Constants.BYTE_ONE);
        if (null == placeId){
            return APIResponse.returnFail("场馆id不能为空");
        }
        if (null == categoryId){
            return APIResponse.returnFail("运动项目id不能为空");
        }
        APIResponse result = placeWrapper.setPlaceCategorySaleTimeUnit(placeId, categoryId, timeUnit, startSaleTimeType);
        return result;
    }

    /**
     *  获取场馆项目及最小销售单元
     * @param
     * @return
     */
    @RequestMapping(value = "/getPlaceCategorySaleTimeUnit",method = RequestMethod.POST)
    public APIResponse<?> getPlaceCategorySaleTimeUnit(@RequestBody Map<String, Object> map) {
        Integer placeId = MapUtils.getInteger(map, "placeId");
        return APIResponse.returnSuccess(placeBaseService.getPlaceCategorySaleTimeUnit(placeId));
    }

    /**
     * 测试组合场同步
     * @param
     * @return
     */
    @RequestMapping(value = "/testSyncPlaceSalePlan",method = RequestMethod.POST)
    public APIResponse<?> testSyncPlaceSalePlan(@RequestBody Map<String, Object> map) {
        // TODO
        Integer placeId = MapUtils.getInteger(map, "placeId");
        String objDate = MapUtils.getString(map,"objDate");
        Date date = DateUtils.strToDate(objDate,DateUtils.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS);
        placeUnitSalePlanWrapper.syncPlaceSalePlan(placeId, date);
        return  APIResponse.returnSuccess();
    }
}
